package net.yihang.controller;

import net.yihang.entity.Module;
import net.yihang.mapper.ModuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ModuleController {

    @Autowired
    private ModuleMapper mapper;

    @ResponseBody
    @RequestMapping("/find1")
    public List<Module> find1() {
        long s= System.currentTimeMillis();
        List<Module> top = mapper.find1();
        System.out.println("find1:"+(System.currentTimeMillis()-s)+"ms");
        return top;
    }

    @ResponseBody
    @RequestMapping("/find2")
    public List<Module> find2() {
        long s= System.currentTimeMillis();
        List<Module> all = mapper.find2();
        Map<Integer, Module> map = new HashMap<>();
        List<Module> top = new ArrayList<>();
        for(Module m: all) {
            if(m.getPid() == 0) {
                top.add(m);
            }
            map.put(m.getId(), m);
        }
        for(Module m: all) {
            Module parent = map.get(m.getPid());
            if(parent != null){
                parent.getChildren().add(m);
            }
        }
        System.out.println("find2:"+(System.currentTimeMillis()-s)+"ms");
        return top;
    }

    @ResponseBody
    @RequestMapping("/find3")
    // easyui 传递过来的参数名为id，但实际是pid
    public List<Module> find3(@RequestParam(defaultValue = "0") int id) {
        long s= System.currentTimeMillis();
        List<Module> top = mapper.find3(id);
        System.out.println("find3:"+(System.currentTimeMillis()-s)+"ms");
        return top;
    }
}
